<?php

namespace app\common\model;

use think\Db;
use think\Model;

class CourseSchedule extends Model
{
    // 表名
    protected $name = 'course_schedule';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 追加属性
    public $append = [
        'course_text',
        'community_text',
        'time_zone_text',
        'time_slot_text',
        'publicwelfare_id_text'
    ];
    
    // 课程列表
    public static function getCourseList($publicwelfare_id = 0,$community_id = 0)
    {
        // 从会话中获取默认值（如果没有提供参数）
        if (empty($community_id) && isset($_SESSION['think']['admin']['community_id'])) {
            $community_id = $_SESSION['think']['admin']['community_id'];
        }
        
        if (empty($publicwelfare_id) && isset($_SESSION['think']['admin']['publicwelfare_id'])) {
            $publicwelfare_id = $_SESSION['think']['admin']['publicwelfare_id'];
        }
        
        // 从数据库读取课程列表
        $query = \think\Db::name('fa_community_course_config')
            ->where('status', 1)
            ->where('delete_time', null);
            
        // 根据条件过滤
        if ($community_id > 0) {
            $query->where('community_id', $community_id);
        }
        
        if ($publicwelfare_id > 0) {
            $query->where('publicwelfare_id', $publicwelfare_id);
        }
        
        // 获取数据并格式化为字典
        $courses = $query->field('id, code, name')->select();
        
        $list = [];
        foreach ($courses as $course) {
            // 优先使用code作为键，如果没有则使用id
            $key = !empty($course['code']) ? $course['code'] : $course['id'];
            $list[$key] = $course['name'];
        }
        
        // 如果没有数据，返回默认列表
        if (empty($list)) {
            return [
                '1' => '音乐',
                '2' => '舞蹈',
                '3' => '书法',
                '4' => '绘画',
                '5' => '钢琴',
                '6' => '太极',
                '7' => '剪纸',
                '8' => '中医',
                '9' => '国画',
                '10' => '生活',
                '11' => '运动',
                '12' => '主持'
            ];
        }
        
        return $list;
    }

    static function getCourseNameList($publicwelfare_id = 0){
        // 从会话中获取默认值（如果没有提供参数）
        if (empty($community_id) && isset($_SESSION['think']['admin']['community_id'])) {
            $community_id = $_SESSION['think']['admin']['community_id'];
        }

        if (empty($publicwelfare_id) && isset($_SESSION['think']['admin']['publicwelfare_id'])) {
            $publicwelfare_id = $_SESSION['think']['admin']['publicwelfare_id'];
        }
        // 从数据库读取课程列表
        $query = \think\Db::name('fa_community_course_config')
            ->where('status', 1)
            ->where('delete_time', null);
        $query->where('publicwelfare_id', $publicwelfare_id);
        $courses = $query->field('id, code, name')->select();
        $list = [];
        foreach ($courses as $course) {
            // 优先使用code作为键，如果没有则使用id
            $key = !empty($course['code']) ? $course['code'] : $course['id'];
            $list[$key] = $course['name'];
        }
        return $list;
    }
    
    // 社区列表
    public static function getCommunityList($publicwelfare_id = 0, $community_id = 0)
    {
        // 从会话中获取默认值（如果没有提供参数）
        if (empty($community_id) && isset($_SESSION['think']['admin']['community_id'])) {
            $community_id = $_SESSION['think']['admin']['community_id'];
        }
        
        if (empty($publicwelfare_id) && isset($_SESSION['think']['admin']['publicwelfare_id'])) {
            $publicwelfare_id = $_SESSION['think']['admin']['publicwelfare_id'];
        }
        
        // 从数据库读取社区列表
        $query = \think\Db::name('fa_community_code_config')
            ->where('status', 1)
            ->where('delete_time', null);
            
        // 根据条件过滤
        if ($community_id > 0) {
            $query->where('community_id', $community_id);
        }
        
        if ($publicwelfare_id > 0) {
            $query->where('publicwelfare_id', $publicwelfare_id);
        }
        
        // 获取数据并格式化为字典
        $communities = $query->field('id, code, name')->select();
        
        $list = [];
        foreach ($communities as $community) {
            // 优先使用code作为键，如果没有则使用id
            $key = !empty($community['code']) ? $community['code'] : $community['id'];
            $list[$key] = $community['name'];
        }
        
        // 如果没有数据，返回默认列表
        if (empty($list)) {
            $list = [];
            for ($i = 1; $i <= 24; $i++) {
                $list[$i] = chr(64 + $i) . '社区'; // A-Z社区
            }
        }
        
        return $list;
    }
    
    // 时区列表
    public static function getTimeZoneList($publicwelfare_id = 0, $community_id = 0)
    {
        // 从会话中获取默认值（如果没有提供参数）
        if (empty($community_id) && isset($_SESSION['think']['admin']['community_id'])) {
            $community_id = $_SESSION['think']['admin']['community_id'];
        }
        
        if (empty($publicwelfare_id) && isset($_SESSION['think']['admin']['publicwelfare_id'])) {
            $publicwelfare_id = $_SESSION['think']['admin']['publicwelfare_id'];
        }
        
        // 从数据库读取时区列表
        $query = \think\Db::name('community_timezone_config')
            ->where('status', 1)
            ->where('delete_time', null);
            
        // 根据条件过滤
        if ($community_id > 0) {
            $query->where('community_id', $community_id);
        }
        
        if ($publicwelfare_id > 0) {
            $query->where('publicwelfare_id', $publicwelfare_id);
        }
        
        // 获取数据并格式化为字典
        $timezones = $query->field('id, code, name')->select();
        
        $list = [];
        foreach ($timezones as $timezone) {
            // 优先使用code作为键，如果没有则使用id
            $key = !empty($timezone['code']) ? $timezone['code'] : $timezone['id'];
            $list[$key] = $timezone['name'];
        }
        
        // 如果没有数据，返回默认列表
        if (empty($list)) {
            $list = [];
            for ($i = 1; $i <= 12; $i++) {
                $list[$i] = '时区' . $i;
            }
        }
        
        return $list;
    }


    public static function getMonthList($publicwelfare_id = 0, $community_id = 0)
    {
        // 从会话中获取默认值（如果没有提供参数）
        if (empty($community_id) && isset($_SESSION['think']['admin']['community_id'])) {
            $community_id = $_SESSION['think']['admin']['community_id'];
        }

        if (empty($publicwelfare_id) && isset($_SESSION['think']['admin']['publicwelfare_id'])) {
            $publicwelfare_id = $_SESSION['think']['admin']['publicwelfare_id'];
        }

        // 从数据库读取时区列表
        $query = \think\Db::name('community_timezone_config')
            ->where('status', 1)
            ->where('delete_time', null);

        // 根据条件过滤
        if ($community_id > 0) {
            $query->where('community_id', $community_id);
        }

        if ($publicwelfare_id > 0) {
            $query->where('publicwelfare_id', $publicwelfare_id);
        }

        // 获取数据并格式化为字典
        $timezones = $query->field('id, name')->select();

        $list = [];
        foreach ($timezones as $timezone) {
            // 优先使用code作为键，如果没有则使用id
            $temp= preg_replace('/^.*年/', '', $timezone['name']);
            $temp= preg_replace('/^0|月/', '', $temp);
            $key = $temp;
            $list[$key] = $timezone['name'];
        }

        // 如果没有数据，返回默认列表
        if (empty($list)) {
            $list = [];
            for ($i = 1; $i <= 12; $i++) {
                $list[$i] = $i;
            }
        }

        return $list;
    }
    
    // 时间段列表
    public static function getTimeSlotList($publicwelfare_id = 0, $community_id = 0, $timezone_id = 0)
    {
        // 从会话中获取默认值（如果没有提供参数）
        if (empty($community_id) && isset($_SESSION['think']['admin']['community_id'])) {
            $community_id = $_SESSION['think']['admin']['community_id'];
        }
        
        if (empty($publicwelfare_id) && isset($_SESSION['think']['admin']['publicwelfare_id'])) {
            $publicwelfare_id = $_SESSION['think']['admin']['publicwelfare_id'];
        }
        
        // 从数据库读取时间段列表
        $query = \think\Db::name('community_timeslot_config')
            ->where('status', 1)
            ->where('delete_time', null);
            
        // 根据条件过滤
        if ($community_id > 0) {
            $query->where('community_id', $community_id);
        }
        
        if ($publicwelfare_id > 0) {
            $query->where('publicwelfare_id', $publicwelfare_id);
        }
        
        if ($timezone_id > 0) {
            $query->where('timezone_id', $timezone_id);
        }
        
        // 获取数据并格式化为字典
        $timeslots = $query->field('id, code, name, day, start_time, end_time')->select();
        
        $list = [];
        foreach ($timeslots as $timeslot) {
            // 优先使用code作为键，如果没有则使用id
            $key = !empty($timeslot['code']) ? $timeslot['code'] : $timeslot['id'];
            
            // 如果 name 字段已经包含完整的显示名称，直接使用
            if (!empty($timeslot['name'])) {
                $list[$key] = $timeslot['name'];
            } else {
                // 否则组合日期和时间
                $startTime = date('H:i', strtotime($timeslot['start_time']));
                $endTime = date('H:i', strtotime($timeslot['end_time']));
                $list[$key] = $timeslot['day'] . '号 ' . $startTime . '-' . $endTime;
            }
        }
        
        // 如果没有数据，返回默认列表
        if (empty($list)) {
            $days = [20, 25, 30];
            $times = [
                '上午8:30-9:10',
                '上午9:20-10:10',
                '下午15:00-15:50'
            ];
            
            $list = [];
            $index = 1;
            foreach ($days as $day) {
                foreach ($times as $time) {
                    $list[$index] = $day . '号' . $time;
                    $index++;
                }
            }
        }
        
        return $list;
    }
    
    // 获取课程文本
    public function getCourseTextAttr($value, $data)
    {
        return isset($data['course_id']) ? self::getCourseText($this->publicwelfare_id, $data['course_id']) : $value;
    }
    
    public function getCommunityTextAttr($value, $data)
    {
        return isset($data['community_id']) ? self::getCommunityText($this->publicwelfare_id, $data['community_id']) : $value;
    }
    
    public function getTimeZoneTextAttr($value, $data)
    {
        return isset($data['time_zone_id']) ? self::getTimeZoneText($this->publicwelfare_id, $data['time_zone_id']) : $value;
    }
    
    public function getTimeSlotTextAttr($value, $data)
    {
        return isset($data['time_slot_id']) ? self::getTimeSlotText(
            $this->publicwelfare_id,
            $data['time_slot_id'] ?? 0,
        ) : $value;
    }
    
    // 获取公益项目文本
    public function getPublicwelfareIdTextAttr($value, $data)
    {
        // 如果需要从数据库获取公益项目名称，可以实现这个方法
        if (isset($data['publicwelfare_id']) && $data['publicwelfare_id'] > 0) {
            $project = \think\Db::name('fa_community_publicwelfare')
                ->where('id', $data['publicwelfare_id'])
                ->field('project_name')
                ->find();
            return $project ? $project['project_name'] : '';
        }
        return '';
    }

    public static function getTimeSlotText($publicwelfare_id = 0, $code=''){
        $result=db("fa_community_timeslot_config")
            ->where('publicwelfare_id', $publicwelfare_id)
            ->where('code', $code)
            ->field('CONCAT(start_time," ", end_time) as name')
            ->select();
            if (!empty($result) && isset($result[0]['name'])) {
                $result[0]['name'] = mb_convert_encoding($result[0]['name'], 'UTF-8', 'auto');
                return $result[0]['name'];
            }
            
            return '';
    }

    public static function getCommunityText($publicwelfare_id = 0, $code=''){
        $result=db("fa_community_code_config")
            ->where('publicwelfare_id', $publicwelfare_id)
            ->where('code', $code)
            ->field('name')
            ->select();
            if (!empty($result) && isset($result[0]['name'])) {
                $result[0]['name'] = mb_convert_encoding($result[0]['name'], 'UTF-8', 'auto');
                return $result[0]['name'];
            }
            
            return '';
    }

    public static function getTimeZoneText($publicwelfare_id = 0, $code=''){
        $result=db("fa_community_timezone_config")
            ->where('publicwelfare_id', $publicwelfare_id)
            ->where('code', $code)
            ->field('name')
            ->select();
            if (!empty($result) && isset($result[0]['name'])) {
                $result[0]['name'] = mb_convert_encoding($result[0]['name'], 'UTF-8', 'auto');
                return $result[0]['name'];
            }
            
            return '';
    }

    public static function getCourseText($publicwelfare_id = 0, $code=''){
        $result=db("fa_community_course_config")
            ->where('publicwelfare_id', $publicwelfare_id)
            ->where('code', $code)
            ->field('name')
            ->select();
            if (!empty($result) && isset($result[0]['name'])) {
                $result[0]['name'] = mb_convert_encoding($result[0]['name'], 'UTF-8', 'auto');
                return $result[0]['name'];
            }
            
            return '';
    }


    /**
     * 处理字段值
     * @param mixed $value
     * @param string $field
     * @param string $fieldType
     * @return mixed
     */
    protected function processFieldValue($value, $field = '', $fieldType = '')
    {
        // 处理空值
        if ($value === '' || $value === null) {
            return null;
        }
        
        // 处理空白字符串
        if (is_string($value) && trim($value) === '') {
            return null;
        }
        
        // 根据字段类型处理值
        if (empty($fieldType)) {
            $fieldType = $this->getFieldType($field);
        }
        if (!empty($fieldType)) {
            return $this->convertByFieldType($value, $fieldType);
        }
        
        return $value;
    }

    /**
     * 获取字段类型
     * @param string $field
     * @return string
     */
    protected function getFieldType($field)
    {
        static $fieldTypes = [];
        $table = $this->getTable();

        if (!isset($fieldTypes[$table])) {
            try {
                $fields = \think\Db::query("SHOW COLUMNS FROM `{$table}`");
                $fieldTypes[$table] = [];
                foreach ($fields as $fieldInfo) {
                    $fieldTypes[$table][$fieldInfo['Field']] = $fieldInfo['Type'];
                }
            } catch (\Exception $e) {
                $fieldTypes[$table] = [];
            }
        }

        return isset($fieldTypes[$table][$field]) ? $fieldTypes[$table][$field] : '';
    }

    /**
     * 根据字段类型转换值
     * @param mixed $value
     * @param string $fieldType
     * @return mixed
     */
    protected function convertByFieldType($value, $fieldType)
    {
        // 整数类型
        if (preg_match('/^(tinyint|smallint|mediumint|int|bigint)/', $fieldType)) {
            return ($value === '' || $value === null) ? null : (int)$value;
        }

        // 浮点数类型
        if (preg_match('/^(float|double|decimal)/', $fieldType)) {
            return ($value === '' || $value === null) ? null : (float)$value;
        }

        // 字符串类型
        if (preg_match('/^(varchar|char|text|longtext|mediumtext|tinytext)/', $fieldType)) {
            return ($value === null) ? null : (string)$value;
        }

        // 日期时间类型
        if (preg_match('/^(datetime|timestamp)/', $fieldType)) {
            if ($value === '' || $value === null) {
                return null;
            }
            return (is_string($value) && strtotime($value) !== false) ? $value : null;
        }

        // 日期类型
        if (preg_match('/^date$/', $fieldType)) {
            if ($value === '' || $value === null) {
                return null;
            }
            return (is_string($value) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) && strtotime($value) !== false) ? $value : null;
        }

        // 时间类型
        if (preg_match('/^time$/', $fieldType)) {
            if ($value === '' || $value === null) {
                return null;
            }
            return (is_string($value) && preg_match('/^\d{2}:\d{2}:\d{2}$/', $value)) ? $value : null;
        }

        return $value;
    }

    /**
     * 判断给定publicwelfare_id的项目是否为正式排课
     * @param int $publicwelfare_id 项目ID
     * @return bool
     */
    public function isFormalSchedule($publicwelfare_id)
    {
        $formalCount = model('Autoplan')->where('publicwelfare_id', $publicwelfare_id)->count();
        $tempCount = model('Autoplantemp')->where('publicwelfare_id', $publicwelfare_id)->count();

        return ($formalCount > 0 && $tempCount == 0);
    }


    /**
     * 转义SQL值
     * @param mixed $value
     * @return string
     */
    protected function escapeValue($value)
    {
        if (is_string($value)) {
            return "'" . addslashes($value) . "'";
        } elseif (is_numeric($value)) {
            return $value;
        } elseif (is_bool($value)) {
            return $value ? '1' : '0';
        } else {
            return "'" . addslashes((string)$value) . "'";
        }
    }


    function getCourseCodeFromName($publicwelfare_id)
    {
        $results = Db::name('fa_community_course_config')->field('code,id')->where("publicwelfare_id",$publicwelfare_id)->select();
        $result=array();
        foreach($results as $key=>$val){
            $result[$val['code']] = $val['id'];
        }
        return $result;
    }
}